﻿using KonachanChanger.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Text;

namespace KonachanChanger.API
{

    public class TagCollection : List<TagCollection.TagInfo>
    {
        public static TagCollection LoadTagInfo(string tagname)
        {
            try
            {
                WebClient wc = new WebClient();
                var stream = wc.OpenRead(String.Format("http://konachan.com/tag.json?name={0}&limit=0", tagname));
                var tags = Serialization.ReadObject<TagCollection>(stream, Serialization.SerializationType.json);
                var local = LocalDb.GetInstance();
                foreach (var tag in tags)
                {
                    if (tag.Name.Contains("\"") && tag.Name != tagname)
                        continue; //Icky!
                    if (local.Tags.ContainsKey(tag.Name))
                    {
                        var old = local.Tags[tag.Name];
                        local.SetTagData(new API.TagCollection.TagInfo()
                        {
                            Name = tag.Name,
                            Count = tag.Count,
                            Type = tag.Type,
                            LocalCount = old.LocalCount
                        });
                    }
                    else
                        local.SetTagData(tag);
                }

                return tags;
            }
            catch (WebException)
            {
                return new TagCollection();
            }
        }


        [DataContract(Name = "tag")]
        public struct TagInfo
        {
            //[DataMember]
            //int id;
            [DataMember(Name="name")]
            public string Name;
            [DataMember(Name = "count")]
            public int Count;
            [DataMember(Name = "type")]
            public TagType Type;
            [DataMember]
            public int LocalCount { get; set; }
        }
      public  enum TagType
        {
            General = 0, artist = 1, copyright = 3, character = 4
        }
    }
}
